var ProductListData;
var ListSupplier;
var itemPerPage = 10;
$(document).ready(function(){
	loadTable();
	$(".act_icon_view").hide();
	$("#btn_search").click($.fn.SEARCH_RESULT);
	$("#btn_add").click($.fn.GO_UPDATE);
	$("img[id^='icon_view_img']").click($.fn.SHOW_IMG);
	$( "#dialog-message" ).dialog({
		modal: true,
		autoOpen: false,
		buttons: {
			'ok': function() {
				$( this ).dialog( "close" );
			}
		}
	});
	
	var options = { 
		//target:   '#output',   // target element(s) to be updated with server response 
		beforeSubmit:  beforeSubmit,  // pre-submit callback 
		success:       afterSuccess,  // post-submit callback 
		uploadProgress: OnProgress, //upload progress callback 
		resetForm: true        // reset the form after successful submit 
	}; 
	
	$('#data_section').submit(function() { 
		$(this).ajaxSubmit(options);  			
		// always return false to prevent standard browser submit and page navigation 
		return false; 
	}); 
	
	
	
});

$.fn.GO_UPDATE = function (){
	$(".show_img").attr('src','');
	$(".show_img").hide();
	getDirectorList();
	getHospitalList();
	if($(this).attr('action_goto') == 'EDIT'){
		getEditData($(this).attr('key_id'));
	}else{
		setSliderIns(0,0);
		$("#ins_director").combobox();
		$("#ins_hospital").combobox();
	}
	
	$("#hidden_department_code").val($(this).attr('key_id'));
	$("#action_to_update").val($(this).attr('action_goto'));
	$( "#dialog-data_section" ).dialog({
		modal: true,
		width: 600,
		height:400,
		buttons: {
			'submit': function() {
				$('#data_section').submit();
//				$( this ).dialog( "close" );
			},
			'cancel': function(e) {
				$("select").combobox('destroy');
				$('#data_section')[0].reset();
				$( this ).dialog( "close" );
			}
		}
	});
};

$.fn.GO_DELETE = function(){
	
	var key_id = $(this).attr('key_id');
	var action = $("#search_frm").attr('action');
	$( "#dialog-message-confirm_delete" ).dialog({
		modal: true,
		buttons: {
			'delete': function() {
				$( this ).dialog( "close" );
				$.ajax({
					 type: "GET",
					 url: action,
					 data: {
						 id : key_id,
						 action : "DELETE"
						 },
					 dataType: "json",
					 success: function(data){
						 if(data[data.length - 1]){
							 loadTable("","");
						 } else {
							 $("#p_freetext").html('Cannot delete this item!');
							 $( "#dialog-message" ).dialog('open');
						 }
					 },
					error : function(xhr, ajaxOptions, thrownError) {
						$("#p_freetext").html('Error while processing '+xhr+" :: "+thrownError);
						 $( "#dialog-message" ).dialog('open');
					}
				});
			},
			'cancel': function() {
				$( this ).dialog( "close" );
			}
		}
	});
};

$.fn.SEARCH_RESULT = function() {
	loadTable();
};

function loadTable(){
	var datas = $("#search_frm").serializeArray();
	var action = $("#search_frm").attr('action');
	$.ajax({
		 type: "GET",
		 url: action,
		 data: datas,
		 dataType: "json",
		 success: function(data){
			 ProductListData = data;
			 var tableLayout = genTable(data, 1);
			 $("#dataTbody").html(tableLayout);
			 $(".act_icon_edit").click($.fn.GO_UPDATE);
			 $(".act_icon_delete").click($.fn.GO_DELETE);
		 },
		error : function(xhr, ajaxOptions, thrownError) {
			alert("Error while processing.");
		}
	});
}

function genTable(data, pages){
	var totalRecords = data.length;
	var maxPage = Math.ceil(totalRecords / itemPerPage);
	var i = 0;
	var loops = totalRecords;
	if(pages > 1){
		i = ((parseInt(pages) * itemPerPage) - itemPerPage);
	}
	if(maxPage > pages){
		loops = i + itemPerPage;
	}
	var tableLayout = "";
	for(; i<loops; i++){
		tableLayout += "<tr id='"+data[i].hospitalDepartmentCode+"'>" +
						"<td align='center'>" +
						"<img class='act_icon_edit' src='images/datamanage/edit.png' width='20' height='20' key_id='"+data[i].hospitalDepartmentCode+"' action_goto='EDIT'>&nbsp;&nbsp;" +
						"<img class='act_icon_delete' src='images/datamanage/delete.png' width='20' height='20' key_id='"+data[i].hospitalDepartmentCode+"'></td>" +
						"<td>"+data[i].hospitalDepartmentNameTh+"/"+data[i].hospitalDepartmentNameEn+"</td>" +
						"<td>"+data[i].bedCapacityMin+"-"+data[i].bedCapacityMax+"</td>" +
						"<td>"+data[i].director.personTitle+""+data[i].director.personFirstName+" "+data[i].director.personLastName+"</td>" +
						"<td>"+data[i].hospital.hospitalNameTH+"/"+data[i].hospital.hospitalNameEN+"</td>" +
						"</tr>";
	}
	tableLayout += "</tr><tr class='tr_th'><td colspan='10' align='center'>"+	genNumPageList(pages, totalRecords)+"</td>";
	return tableLayout;
}

function genNumPageList(page, totalRecord){
	var numpageLayout = "";
	var totalPage = 1;
	if(totalRecord > itemPerPage){
		totalPage = Math.ceil((totalRecord / itemPerPage)); 
	}
	for(var i=1; i<=totalPage;i++){
		if(i == page){
			numpageLayout += "<b>"+i+"</b>&nbsp;";
		}else{
			numpageLayout += "<span class='spn_numpage' onclick='gotoPage("+i+")'>"+i+"</span>&nbsp;";
		}
	}
	return numpageLayout;
}

function gotoPage(index){
	var tableLayout = genTable(ProductListData, index);
	$("#dataTbody").html(tableLayout);
}

function getEditData(key_id){
	var action = $("#search_frm").attr('action');
	$.ajax({
		 type: "GET",
		 url: action,
		 data: {
			 id : key_id,
			 action : "GETEDIT"
			 },
		 dataType: "json",
		 success: function(data){
			 if(data[data.length - 1]){
				 setFieldEdit(data);
			 } else {
				 $("#p_freetext").html('Cannot get item data!');
				 $( "#dialog-message" ).dialog('open');
			 }
		 },
		error : function(xhr, ajaxOptions, thrownError) {
			$("#p_freetext").html('Error while processing '+xhr+" :: "+thrownError);
			 $( "#dialog-message" ).dialog('open');
		}
	});
}

function setFieldEdit(data){
	$("#hidden_department_code").val(data[0].hospitalDepartmentCode);
	$("#ins_department_name_th").val(data[0].hospitalDepartmentNameTh);
	$("#ins_department_name_en").val(data[0].hospitalDepartmentNameEn);
	setSliderIns(data[0].bedCapacityMin, data[0].bedCapacityMax);
	var presidentLoop = $("#ins_director option").length;
	for(var i=0; i<presidentLoop; i++){
		if(data[0].director.personCode == $("#ins_director option").eq(i).val()){
			$("#ins_director option").eq(i).attr('selected', 'selected');
		}
	}
	$("#ins_director").combobox();
	
	var hospitalLoop = $("#ins_hospital option").length;
	for(var i=0; i<hospitalLoop; i++){
		if(data[0].hospital.hospitalCode == $("#ins_hospital option").eq(i).val()){
			$("#ins_hospital option").eq(i).attr('selected', 'selected');
		}
	}
	$("#ins_hospital").combobox();
}

function getDirectorList(){
	var action = $("#search_frm").attr('action');
	$.ajax({
		 type: "GET",
		 url: action,
		 data: {
			 action : "GETPERSON"
			 },
		 dataType: "json",
		 success: function(data){
			 if(data[data.length - 1]){
				 setPersonList(data);
			 } else {
				 $("#p_freetext").html('Could not load director list!');
				 $( "#dialog-message" ).dialog('open');
			 }
		 },
		error : function(xhr, ajaxOptions, thrownError) {
			$("#p_freetext").html('Error while processing '+xhr+" :: "+thrownError);
			 $( "#dialog-message" ).dialog('open');
		}
	});
}

function setPersonList(data){
	var loop = data.length - 1;
	var str = "<option value=''>Please select..</option>";
	for (var i=0; i< loop; i++){
		str += "<option value='"+data[i].personCode+"'>"+data[i].personTitle+data[i].personFirstName+" "+data[i].personLastName+"</option>";
	}
	$("#ins_director").html(str);
	
}

function getHospitalList(){
	var action = $("#search_frm").attr('action');
	$.ajax({
		 type: "GET",
		 url: action,
		 data: {
			 action : "GETHOSPITAL"
			 },
		 dataType: "json",
		 success: function(data){
			 if(data[data.length - 1]){
				 setHospitalList(data);
			 } else {
				 $("#p_freetext").html('Could not load director list!');
				 $( "#dialog-message" ).dialog('open');
			 }
		 },
		error : function(xhr, ajaxOptions, thrownError) {
			$("#p_freetext").html('Error while processing '+xhr+" :: "+thrownError);
			 $( "#dialog-message" ).dialog('open');
		}
	});
}

function setHospitalList(data){
	var loop = data.length - 1;
	var str = "<option value=''>Please select..</option>";
	for (var i=0; i< loop; i++){
		str += "<option value='"+data[i].hospitalCode+"'>"+data[i].hospitalNameTH+" "+data[i].hospitalNameEN+"</option>";
	}
	$("#ins_hospital").html(str);
	
}

function setSliderIns(minVal, maxVal){
	$( "#ins_bed-capacity-range" ).slider({
	      range: true,
	      min: 0,
	      max: 700,
	      values: [ parseInt(minVal), parseInt(maxVal) ],
	      slide: function( event, ui ) {
	    	  $("#ins_bed_min").val(ui.values[ 0 ]);
	    	  $("#ins_bed_max").val(ui.values[ 1 ]);
	      }
	});
	$("#ins_bed_min").val($( "#ins_bed-capacity-range" ).slider( "values", 0 ));
	$("#ins_bed_max").val($( "#ins_bed-capacity-range" ).slider( "values", 1 ));
	$("#ins_bed_min").keyup(function(){
		var regexp = /^[+]?\d+$/;
		if(regexp.test($(this).val())){
			$("#ins_bed-capacity-range").slider("values", 0, $(this).val());
		}
	});
	$("#ins_bed_max").keyup(function(){
		var regexp = /^[+]?\d+$/;
		if(regexp.test($(this).val())){
			$("#ins_bed-capacity-range").slider("values", 1, $(this).val());
		}
	});
}

function afterSuccess()
{
//	$('#submit-btn').show(); //hide submit button
	
	loadTable("","");
	$('#loading-img').hide(); //hide submit button
	$('#progressbox').delay( 1000 ).fadeOut(); //hide progress bar

}

//function to check file size before uploading.
function beforeSubmit(){
	
    //check whether browser fully supports all File API
   if (window.File && window.FileReader && window.FileList && window.Blob)
	{
	  
	    $( "#dialog-data_section" ).dialog('close');
		$('#loading-img').show(); //hide submit button
		$("#output").html(""); 
		 
	}
	else
	{
		//Output error to older unsupported browsers that doesn't support HTML5 File API
		$("#output").html("Please upgrade your browser, because your current browser lacks some new features we need!");
		return false;
	}
}


//progress bar function
function OnProgress(event, position, total, percentComplete)
{
    //Progress bar
	$('#progressbox').show();
    $('#progressbar').width(percentComplete + '%'); //update progressbar percent complete
    $('#statustxt').html(percentComplete + '%'); //update status text
    if(percentComplete>50)
        {
            $('#statustxt').css('color','#000'); //change status text to white after 50%
        }
}

//function to format bites bit.ly/19yoIPO
function bytesToSize(bytes) {
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
   if (bytes == 0) return '0 Bytes';
   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}